from django.http import HttpResponse
from dsp.core.models import Post, Tag
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
import datetime,os
from django.conf import settings
from django.template import RequestContext



def blog(request):
	latest_posts = Post.objects.all().order_by('-date')[:5]
  	return render_to_response('index.html', {'latest_posts': latest_posts}, context_instance=RequestContext(request))

def view_tag(request, name):

		tag = Tag.objects.get(pk=name)
		posts = tag.post_set.all()

		return render_to_response("tags.html", {"tag_name":tag, "posts":posts}, context_instance=RequestContext(request))


def view_post(request, title):

	try:
		post = Post.objects.get(slug=title)

	except Post.DoesNotExist:

		name = ""
		content = ""
		date = ""
		

	tags = title.tags.all()
	
	return render_to_response("single.html", {"post":post, "tags":tags}, context_instance=RequestContext(request))

def write(request):

	f = open('templates/rawr.txt','w')
	f.write('test')
	f.close()
	
	
	return render_to_response("theme.html", context_instance=RequestContext(request))


def read(request):
	f = open('templates/rawr.txt','r')
	content = f.read()
	f.close()
	
	return render_to_response("theme.html", {"content":content}, context_instance=RequestContext(request))


def themehome(request):

	for root, dirs, files in os.walk('./'):
  		for name in files:       
      			filename = os.path.join(root, name)
      			print filename


	return render_to_response('theme.html', context_instance=RequestContext(request))


def edittheme(request,name):
	
      	filelocation = 'templates/theme/' + name + '.html'
	f = open(filelocation,'r')
	content = f.read()
	f.close()

	return render_to_response('theme.html', {'content': content, 'filename':name} ,context_instance=RequestContext(request))


def savetheme(request):

	if request.method == 'POST': # If the form has been submitted...

		content = request.POST['theme']
		name = request.POST['name']

      		filelocation = 'templates/theme/' + name + '.html'
       		
		f = open(filelocation,'w')
		f.write(content)
		f.close()

       	return HttpResponseRedirect('index')




